// src/utils/request.js
import Taro from '@tarojs/taro'

const BASE_URL = 'https://restapi.amap.com/v3/weather/weatherInfo'

class HttpRequest {
  constructor() {
    this.timeout = 10000
  }

  async request(url, data = {}, method = 'GET') {
    try {
      const response = await Taro.request({
        url: `${BASE_URL}${url}`,
        data,
        method,
        timeout: this.timeout,
        header: {
          'Content-Type': 'application/json'
        }
      })

      // 更健壮的状态码检查
      const statusCode = response?.statusCode || response?.status || 0
      
      if (statusCode >= 200 && statusCode < 300) {
        return response.data
      } else {
        throw new Error(`网络请求失败: ${statusCode}`)
      }
    } catch (error) {
      console.error('Request error:', error)
      throw error
    }
  }

  get(url, data = {}) {
    return this.request(url, data, 'GET')
  }

  post(url, data = {}) {
    return this.request(url, data, 'POST')
  }
}

export const httpRequest = new HttpRequest()